//
//  CommodityTools.m
//  FMDB_Demo_Login
//
//  Created by libertyair on 15/5/29.
//  Copyright (c) 2015年 libertyair. All rights reserved.
//

#import "CommodityTools.h"
#import "FMDB.h"

@implementation CommodityTools


static FMDatabase *db = nil;
+ (void)initialize
{
    // 0.获得沙盒中的数据库文件名
    NSString *filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.sql"];
    
    // 1.创建数据库实例对象
    db = [FMDatabase databaseWithPath:filename];
    NSLog(@"%@",filename);
    // 2.打开数据库
    if ( [db open] )
    {
        LALog(@"数据库打开成功");
        
        // 创表
        BOOL result = [db executeUpdate:@"create table if not exists t_commodity (name text, number text primary key sprice real,iprice real,category text,count integer);"];  //count 表示库存
        
        if (result)
            LALog(@"创表成功");
        else
            LALog(@"创表失败");
    }
    else
        LALog(@"数据库打开失败");
    
}


/*
 添加新商品
 采购不要调用这个方法
 */
+ (BOOL)addCommodities:(Commodity *)commodity andCount:(NSInteger)count
{
    return [db executeUpdate:@"insert into t_commodity (name,number,sprice,iprice,category,count) values (?,?,?,?,?,?);",commodity.name,commodity.number,commodity.sPrice,commodity.iPrice,commodity.category,count];
}

///*
// 查询是否有这个商品
// */
//+ (BOOL)searchCommodity:(Commodity *)commodity
//{
//    // 1.查询数据
//    FMResultSet *rs = [db executeQuery:@"select * from t_commodity where number = ? and name = ?;", commodity.number,commodity.name];
//    
//    // 2.遍历结果集
//    while (rs.next) {
//
//        return YES;
//    }
//    return NO;
//}

/*
 更新商品信息
 */
+ (BOOL)updateCommodity:(Commodity *)oldCommodity newCommodity:(Commodity *)newCommodity andCount:(NSInteger)newCount;
{
    [db executeUpdate:@"update t_commodity set name = %@,number = %ld, sprice = %lf,iprice = %lf,category = %@,count = %ld where number = %ld",newCommodity.name,newCommodity.number,newCommodity.sPrice,newCommodity.iPrice,newCommodity.category,newCount, oldCommodity.number];

    return YES;
}

/*
 采购或售出
 */
+ (BOOL)transactionCommodity:(Commodity *)commodity andCount:(NSInteger)count
{
    // 1.查询数据
    FMResultSet *rs = [db executeQuery:@"select * from t_commodity where number = ? and name = ?;", commodity.number,commodity.name];

    // 2.遍历结果集
    while (rs.next) {
        NSInteger tempCount = [rs intForColumn:@"count"]+count;
    
        return [self updateCommodity:commodity newCommodity:commodity andCount:tempCount];
    }
    return NO;
}

@end








